package com.stud.seckill.controller;

import cn.dev33.satoken.stp.StpUtil;
import cn.hutool.core.util.StrUtil;
import com.stud.seckill.service.LoginService;
import com.stud.seckill.entity.vo.LoginVo;
import com.stud.seckill.common.vo.R;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletResponse;
import javax.validation.Valid;

@Slf4j
@Controller
@RequestMapping("/login")
public class LoginController {

    @Autowired
    private LoginService loginService;

    /**
     * 登录页
     * @return
     */
    @GetMapping("/toLogin")
    public String toLogin() {
        if (StpUtil.isLogin()) {
            return "redirect:/goods/toList";
        }
        return "login";
    }

    /**
     * 登录
     * @return
     */
    @ResponseBody
    @PostMapping("/doLogin")
    public R<String> doLogin(@Valid LoginVo entity, HttpServletResponse response) {
        log.info("登录信息：{}", entity);
        if (StrUtil.isEmpty(entity.getMobile())) {
            return R.fail("请输入手机号");
        }
        if (StrUtil.isEmpty(entity.getPassword())) {
            return R.fail("请输入密码");
        }
        return loginService.doLogin(entity, response);
    }

    // 查询登录状态，浏览器访问： http://localhost:8081/user/isLogin
    @ResponseBody
    @RequestMapping("/isLogin")
    public R<String> isLogin() {
        return R.success("当前会话是否登录：" + StpUtil.isLogin());
    }

}
